package com.lineage.server.world;

import com.lineage.server.model.L1War;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WorldWar {
  private static final Log _log = LogFactory.getLog(WorldWar.class);
  
  private static WorldWar _instance;
  
  private final CopyOnWriteArrayList<L1War> _allWars;
  
  private List<L1War> _allWarList;
  
  public static WorldWar get() {
    if (_instance == null)
      _instance = new WorldWar(); 
    return _instance;
  }
  
  private WorldWar() {
    this._allWars = new CopyOnWriteArrayList<>();
  }
  
  public void addWar(L1War war) {
    try {
      if (!this._allWars.contains(war))
        this._allWars.add(war); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public void removeWar(L1War war) {
    try {
      if (this._allWars.contains(war))
        this._allWars.remove(war); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public List<L1War> getWarList() {
    try {
      List<L1War> vs = this._allWarList;
      return (vs != null) ? vs : (this._allWarList = Collections.unmodifiableList(this._allWars));
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
      return null;
    } 
  }
  
  public boolean isWar(String clanname, String tgclanname) {
    try {
      Iterator<L1War> iterator = this._allWars.iterator();
      while (iterator.hasNext()) {
        L1War war = iterator.next();
        boolean isInWar = war.checkClanInWar(clanname);
        if (isInWar) {
          boolean isInWarTg = war.checkClanInWar(tgclanname);
          if (isInWarTg)
            return true; 
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    return false;
  }
}
